import java.time.LocalDateTime;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 演示读写锁的使用
 */
 class ReadWriteLockDemo1 {
    public static void main(String[] args) {
        //创建读写锁
        final ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();
        //创建读锁
        final ReentrantReadWriteLock.ReadLock readLock=readWriteLock.readLock();
        //创建写锁
        final ReentrantReadWriteLock.WriteLock writeLock=readWriteLock.writeLock();
        //线程池
        ThreadPoolExecutor executor=new ThreadPoolExecutor(5,5,0,
                TimeUnit.SECONDS,new LinkedBlockingDeque<>());
        //启动线程执行任务(读)
        executor.submit(()->{
            //加锁操作
            readLock.lock();
            try{
                //执行业务逻辑
                System.out.println("执行读锁1:"+ LocalDateTime.now());
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally{
                readLock.unlock();
            }
        });

        //启动新线程执行任务(读操作2)
        executor.submit(()->{
            readLock.lock();
            try{
                //执行业务逻辑
                System.out.println("执行读锁2:"+LocalDateTime.now());
                TimeUnit.SECONDS.sleep(3);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                readLock.unlock();
            }
        });

        //创建新线程执行(写操作)
        executor.submit(()->{
            //加锁
            writeLock.lock();
           try{
               //业务逻辑
               System.out.println("执行写锁1:"+LocalDateTime.now());
               TimeUnit.SECONDS.sleep(1);
           } catch (InterruptedException e) {
               e.printStackTrace();
           } finally{
               writeLock.unlock();
            }
        });

        //创建新线程执行写操作
        executor.submit(()->{
            writeLock.lock();
            try{
                //业务逻辑
                System.out.println("执行写锁2:"+LocalDateTime.now());
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                writeLock.unlock();
            }
        });




    }
}

